#include "udpsocketptp.h"

UdpSocketPtP::UdpSocketPtP()
{
    connect(_sock,&QUdpSocket::readyRead,this,[this]()
    {
        while(_sock->hasPendingDatagrams())
        {
            QByteArray datagram;
            datagram.resize(_sock->pendingDatagramSize());
            QHostAddress peerAddr;
            quint16 peerPort;
            _sock->readDatagram(datagram.data(),datagram.size(),&peerAddr,&peerPort);

            emit signal_readMsg(peerAddr.toString(),peerPort,datagram);
        }
    });
}

bool UdpSocketPtP::bind_multicast(QHostAddress ip, uint16_t port)
{
    _localAddress = ip;
    _localPort = port;

    if(_sock->bind(_localAddress, _localPort, QUdpSocket::ShareAddress))
    {
        isConnecting = true;
        qDebug() << "UDPSocket 单播 连接成功...";
        return true;
    }
    else
    {
        isConnecting = false;
        qDebug() << "UDPSocket 单播 连接失败..." << " [ERROR]: " << _sock->errorString();
        return false;
    }
}

void UdpSocketPtP::quit_multicast()
{
    _sock->abort();
    _sock->close();
    isConnecting = false;
    qDebug() << "UDPSocket 单播 关闭连接...";
}

qint64 UdpSocketPtP::send_msg(QByteArray msg, QString addr, int port)
{
   return _sock->writeDatagram(msg,QHostAddress(addr),port);
}
